<!-- checkSquare.svelte -->
<script lang="ts">
	import Icon from '$lib/components/Basic/Icon/Icon.svelte';

	const {
		checked = false,
		indeterminate = false,
		size = 'md',
		disabled = false,
		onChange = () => {}
	} = $props<{
		checked?: boolean;
		indeterminate?: boolean;
		size: 'sm' | 'md' | 'lg';
		disabled?: boolean;
		onChange?: (checked: boolean) => void;
	}>();
	const toggleState = (e:MouseEvent) => {
		if(disabled) return;
		onChange(!checked);
	};
</script>

<div
	class="check-square size--{size} {checked ? 'is-checked' : ''} {indeterminate
		? 'is-indeterminate'
		: ''} {disabled ? 'check-square--disabled' : ''}"
	role="checkbox"
	aria-checked={indeterminate ? 'mixed' : checked}
	aria-disabled={disabled}
	tabindex={disabled ? -1 : 0}
	onclick={toggleState}
	onkeydown={()=>{}}
>
	<div class="check-square-in">
		<!-- 新增占位元素 -->
		<div class="clickable-area"></div>
		<div class="check-square-icon">
			{#if checked}
				<Icon src="form/checked" />
			{:else if indeterminate}
				<Icon src="form/minus" />
			{/if}
		</div>
	</div>
</div>

<style lang="scss" scoped>
	.check-square {
		display: inline-flex;
		align-items: center;
		vertical-align: middle;
		
		&:not(.check-square--disabled) {
			cursor: pointer;
			.check-square-in:hover {
				border-color: var(--checkbox-color);
			}
		}

		&.check-square--disabled {
			cursor: not-allowed;
			opacity: 0.7;
		}
	}

	.size--sm {
		.check-square-in {
			width: 12px;
			height: 12px;
		}
	}

	.size--md {
		.check-square-in {
			width: 13px;
			height: 13px;
		}
	}

	.size--lg {
		.check-square-in {
			width: 14px;
			height: 14px;
		}
	}

	/* 点击区域占位 */
	.clickable-area { 
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 1;
		cursor: inherit;
	}

	.check-square-in {
		position: relative; 
		background-color: var(--color-page);
		border: 1px solid var(--color-info-300);
		border-radius: 2px;
		margin: 3px;
		transition: all 0.2s ease;
		flex-shrink: 0;
		overflow: hidden;
	}

	.check-square-icon {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
		color: var(--color-page);
	}

	/* 非禁用状态 选中/半选 */
	.check-square:not(.check-square--disabled) {
		&.is-checked,
		&.is-indeterminate {
			.check-square-in {
				background-color: var(--checkbox-color);
				border-color: var(--checkbox-color);
			}
		}
	}

	/* 禁用状态 */
	.check-square.check-square--disabled {
		&.is-checked,
		&.is-indeterminate {
			.check-square-in {
				background-color: var(--color-info-100);
				.check-square-icon {
					color: var(--color-info-500);
				}
			}
		}
	}
</style>
